package cate.game.activity.moonfight;

import cate.common.table.activity.moonfight.row.MoonHardLevelRow;
import cate.common.table.activity.moonfight.row.MoonRewardRow;
import cate.common.table.activity.moonfight.row.MoonUnlockRow;
import cate.common.table.d.*;
import cate.common.util.GameResult;
import cate.game.activity.base.core.RoleFarmActivitySingle;
import cate.game.activity.moonfight.msg.MoonFightGlobalInfoResp;
import cate.game.activity.moonfight.msg.MoonFightInfoResp;
import cate.game.activity.moonfight.po.RoundRecord;
import cate.game.mail.po.MailBuilder;
import cate.game.play.part.FightSide;
import cate.game.play.part.PlaySide;
import cate.game.play.proce.play.PlayPO;
import cate.game.res.MixRes;
import cate.game.role.Role;
import cate.game.role.mail.Mail;
import cate.game.role.task.TaskGroup;
import cate.game.role.task.TaskItem;
import easy.java.dev.note.NoteField;
import easy.java.practice.errorcode.EcResult;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MoonFightActivity extends RoleFarmActivitySingle {
    @NoteField("key：阶段，value：通关记录")
    public Map<Integer, RoundRecord> passMap;

    @NoteField("月下比武星星奖励领取记录")
    public Map<Integer, Boolean> record;

    @Override
    public void initialize(Role role) {
        super.initialize(role);
        if (passMap == null) {
            passMap = new HashMap<>();
        }
        passMap.values().forEach(roundRecord -> roundRecord.initialize(role));
        if (record == null) {
            record = new HashMap<>();
        }
    }

    //挑战擂主
    public GameResult<MoonFightActivity> challenge(int round, int rank, int level) {
        GameResult<MoonFightActivity> r = new GameResult<>();
        r.data = this;
        //先判断本阶段是否开启
        MoonUnlockRow roundRow = role.getGame().table.moonFight.unlock.get(round);
        if (roundRow == null) {
            return r.fail("阶段配置不存在");
        }
        if (roundRow.condi1 > 0) {
            int star = passMap.get(roundRow.condi1).passRecord.values().stream().map(i ->
            {
                MoonHardLevelRow row = role.getGame().table.moonFight.hardLevel.getRowByRoundAndHard(roundRow.condi1, i);
                if (row != null) {
                    return row.star;
                }
                return 0;
            }).mapToInt(s -> s).sum();
            if (star < roundRow.condi2) {
                return r.fail("本阶段未开启");
            }
        }
        if (getCurrentDay() < roundRow.day) {
            return r.fail("本阶段未到开启时间");
        }
        MoonHardLevelRow hard = role.getGame().table.moonFight.hardLevel.getRowByRoundAndHard(round, level);
        if (hard == null) {
            return r.fail("找不到对应难度");
        }

        MoonFightActivityHandler handler = role.getGame().activityGlobal.getEnableHandler(GDFunc.MOON_FIGHT);
        if (handler == null) {
            return r.fail("找不到全局数据");
        }
        MoonFightGlobalData globalData = handler.getGlobalData();
        MoonFightBoss boss = globalData.getBoss(round, rank);
        if (boss == null) {
            return r.fail("擂主阵容不存在");
        }
//        if (StringUtils.equals(boss.uid, role.getUid())) {
//            return r.fail("自己都不认识了？");
//        }
        FightSide fsRes = role.getGame().fight.side.createFightSideByPlaySide(GDFight.Team.B, boss.ps);
        EcResult<PlaySide> psR = role.getGame().fight.side.createPlaySideByRole(role, GDFunc.ADVENTURE);
        MoonFightFTC context = new MoonFightFTC(role, funcId, hard, psR.data, rank);
        context.param.sideB.attrAppend.setTeamAttrScale(hard.scale / 10000);
        context.funcId = getFightFuncId();
        context.setPositionApply(GDFunc.ADVENTURE);
        EcResult<PlayPO> fightRes = role.getGame().play.startByRole(role, context, fsRes);
        if (!fightRes.ok()) {
            return r.fail(fightRes.message);
        }
        this.startFighting();
        role.getHistory().action.moonFightChallengeTimes(1);
        return r;
    }

    //领取星星奖励
    public GameResult<MoonFightActivity> takeReward(int tid) {
        GameResult<MoonFightActivity> r = new GameResult<>();
        r.data = this;
        MoonRewardRow row = role.getGame().table.moonFight.reward.get(tid);
        if (row == null) {
            return r.fail("配置不存在");
        }
        if (record.containsKey(tid)) {
            return r.fail("奖励已领取");
        }
//        passMap.get(row.level)
        int star = passMap.get(row.level).passRecord.values().stream().map(i ->
        {
            MoonHardLevelRow lRow = role.getGame().table.moonFight.hardLevel.getRowByRoundAndHard(row.level, i);
            if (lRow != null) {
                return lRow.star;
            }
            return 0;
        }).mapToInt(s -> s).sum();
        if (star < row.star) {
            return r.fail("星星数量不够");
        }
        record.put(tid, true);
        MixRes res = new MixRes(row.reward);
        res.addAndDialog(role, true, GDOperation.MOON_FIGHT_STAR_REWARD, tid);
        return r;
    }

    public void updatePassRecord(int round, int rank, int level) {
        RoundRecord roundRecord = passMap.get(round);
        if (roundRecord == null) {
            roundRecord = new RoundRecord();
            roundRecord.initialize(role);
            passMap.put(round, roundRecord);
        }
        Integer oldLevel = roundRecord.passRecord.get(rank);
        if (oldLevel == null || level > oldLevel) {
            roundRecord.passRecord.put(rank, level);
        }
        noticeUpdate();
    }

    @Override
    public int getFightFuncId() {
        return GDFunc.MOON_FIGHT;
    }

    @Override
    public void onEnter() {
        super.onEnter();
    }


    @Override
    public void initSend() {
        super.initSend();
        noticeUpdate();
        noticeGlobal();
    }


    public void noticeUpdate() {
        role.sendNow(new MoonFightInfoResp(this));
    }

    public void noticeGlobal() {
        MoonFightActivityHandler global = role.getGame().activityGlobal.getEnableHandler(funcId());
        role.sendNow(new MoonFightGlobalInfoResp(global.getGlobalData()));
    }

    @Override
    public void excelCheck() {
        super.excelCheck();
        List<Integer> taskIds = role.getGame().table.moonFight.task.getTaskIds();
        role.getTask().getGroup(funcId()).addItemListNoRepeat(taskIds, false);
    }

    @Override
    public void onDaySpan(boolean silence) {
        super.onDaySpan(silence);
        List<Integer> taskIds = role.getGame().table.moonFight.task.getTaskIds(GDWarOrder.TaskType.DAILY);
        TaskGroup taskGroup = role.getTask().getGroup(funcId());
        taskGroup.removeItemList(taskIds);
        taskGroup.addItemListNoRepeat(taskIds, silence);
    }

    @Override
    public void onRoleOpen() {
        super.onRoleOpen();
        initPass();
    }

    @Override
    public void onRoleEnd() {
        super.onRoleEnd();
        //邮件发送未领取的星星奖励
        sendUntakeReward();
        sendDoneMail();
        passMap.clear();
        record.clear();
    }

    //如果在排行榜上，就要直接给自己通关
    public void initPass() {
        MoonFightActivityHandler handler = role.getGame().activityGlobal.getEnableHandler(funcId());
        MoonFightGlobalData globalData = handler.getGlobalData();
        for (int round : globalData.roundMap.keySet()) {
            MoonFightRound fightRound = globalData.roundMap.get(round);
            for (int rank : fightRound.bossMap.keySet()) {
                if (StringUtils.equals(fightRound.bossMap.get(rank).uid, role.getUid())) {
                    updatePassRecord(round, rank, role.getGame().table.moonFight.hardLevel.getHardest(round));
                    break;
                }
            }
        }

    }

    public void sendUntakeReward() {
        MixRes reward = new MixRes();
        for (MoonRewardRow row : role.getGame().table.moonFight.reward.getList()) {
            if (!record.containsKey(row.id)) {
                int star = passMap.get(row.level).passRecord.values().stream().map(i ->
                {
                    MoonHardLevelRow lRow = role.getGame().table.moonFight.hardLevel.getRowByRoundAndHard(row.level, i);
                    if (lRow != null) {
                        return lRow.star;
                    }
                    return 0;
                }).mapToInt(s -> s).sum();
                if (star >= row.star) {
                    reward.addList(new MixRes(row.reward));
                }
            }
        }
        if (!reward.isEmpty()) {
            sendMail(reward, GDMail.Tid.MOON_FIGHT_STAR_REWARD);
        }
    }

    private void sendMail(MixRes reward, int mailID) {
        MailBuilder mailBuilder = new MailBuilder();
        mailBuilder.setContentId(mailID).setReward(reward.copy())
                .setOperation(GDOperation.MOON_FIGHT_STAR_REWARD);
        role.getMail().add(mailBuilder.build());
    }

    public void sendDoneMail() {
        TaskGroup taskGroup = role.getTask().getGroup(funcId());
        MixRes reward = new MixRes();
        for (TaskItem taskItem : taskGroup.doneList) {
            if (taskItem.done && !taskItem.rewardGot) {
                reward.addList(new MixRes(taskItem.getTpl().rewardStr));
            }
        }
        if (!reward.isEmpty()) {
            Mail mail = new MailBuilder()
                    .setReward(reward)
                    .setContentId(GDMail.Tid.MOON_FIGHT_TASK_REWARD)
                    .setOperation(GDOperation.MOON_FIGHT_TASK_REWARD)
                    .setOperationSub(funcId())
                    .build();
            role.getGame().mail.send(role.getUid(), mail);
        }
        taskGroup.removeAllItems();
    }
}
